var express = require('express');
var router = express.Router();
var sequelize = require('../util/db.js');
var User = require('../models/user.js');
var Pet = require('../models/pet.js');
const Sequelize = require('sequelize');

router.get('/',function(req,res,next){
  sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

});

//关联查询
router.route('/find').get(function(req, res) {
 Pet.findAll({
    include: [{
        model: User
    }]
 }).then(user => {
      res.send( user.get ? user.get('username') : '');
    });
});

router.route('/sql').get(function(req, res) {
    sequelize.query("SELECT * FROM pets").then(myTableRows => {
      console.log(myTableRows)
    })
});

//增加
router.get('/adduser',function(req, res) {
    sequelize.sync()
      .then(() => User.create({
        username: 'janedoe',
        birthday: new Date(1980, 6, 20)
      }))
      .then(jane => {
        console.log(jane.toJSON());
      });
});

//查看
router.get("/user/:id",function(req,res){
    User.findOne({id:req.params.id}).then(user => {
      res.send(user.get('username'));
    });
})

module.exports = router;